﻿//-----------------------------------------------------------------------
// <copyright file="HtmlHelperJavaScriptExtensions.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.Web.UI.Helpers{    using System;
    using System.Web;
    using System.Web.Mvc;
    using AbstractSaaSTemplate.Application.Customization;
    using AbstractSaaSTemplate.Application.Framework;

    /// <summary>
    /// Provides methods that respond to HTTP requests that are made to an ASP.NET
    /// MVC Web site, customised for this application
    /// </summary>
    public static class HtmlHelperJavaScriptExtensions
    {
        /// <summary>
        /// Renders an inclusion to a javascript file, casting it from the right
        /// javascripts repository.
        /// </summary>
        /// <param name="helper">The helper which will be extended</param>
        /// <param name="fileName">The filename which will be extended</param>
        /// <returns>Returns an instance of MvcHtmlString containing the tag</returns>
        public static MvcHtmlString JavaScriptForCore(
            this HtmlHelper helper,
            string fileName)
        {
            return JavaScript(
                helper,
                JavaScriptType.Core,
                string.Empty,
                string.Empty,
                fileName,
                false);
        }

        /// <summary>
        /// Renders an inclusion to a javascript file, casting it from the right
        /// javascripts repository.
        /// </summary>
        /// <param name="helper">The helper which will be extended</param>
        /// <param name="fileName">The filename which will be extended</param>
        /// <returns>Returns an instance of MvcHtmlString containing the tag</returns>
        public static MvcHtmlString JavaScriptForShared(
            this HtmlHelper helper,
            string fileName)
        {
            if (helper == null)
            {
                throw new ArgumentNullException("helper");
            }

            var areaName = GetAreaFromContext(helper.ViewContext);

            return JavaScript(
                helper,
                JavaScriptType.Shared,
                string.Empty,
                string.Empty,
                fileName,
                false);
        }

        /// <summary>
        /// Renders an inclusion to a javascript file, casting it from the right
        /// javascripts repository.
        /// </summary>
        /// <param name="helper">The helper which will be extended</param>
        /// <param name="fileName">The filename which will be extended</param>
        /// <returns>Returns an instance of MvcHtmlString containing the tag</returns>
        public static MvcHtmlString JavaScriptForFont(
            this HtmlHelper helper,
            string fileName)
        {
            return JavaScript(
                helper,
                JavaScriptType.Font,
                string.Empty,
                string.Empty,
                fileName,
                false);
        }

        /// <summary>
        /// Renders an inclusion to a javascript file, casting it from the right
        /// javascripts repository.
        /// </summary>
        /// <param name="helper">The helper which will be extended</param>
        /// <param name="fileName">The filename which will be extended</param>
        /// <returns>Returns an instance of MvcHtmlString containing the tag</returns>
        public static MvcHtmlString JavaScriptForUX(
            this HtmlHelper helper,
            string fileName)
        {
            return JavaScriptForUX(
                helper,
                fileName,
                false);
        }

        /// <summary>
        /// Renders an inclusion to a javascript file, casting it from the right
        /// javascripts repository (it will include the /Partials after the name
        /// of the controller as directory).
        /// </summary>
        /// <param name="helper">The helper which will be extended</param>
        /// <param name="fileName">The filename which will be extended</param>
        /// <returns>Returns an instance of MvcHtmlString containing the tag</returns>
        public static MvcHtmlString JavaScriptForPartialUX(
            this HtmlHelper helper,
            string fileName)
        {
            return JavaScriptForUX(
                helper,
                fileName,
                true);
        }

        /// <summary>
        /// Renders an inclusion to a javascript file, casting it from the right
        /// javascripts repository.
        /// </summary>
        /// <param name="helper">The helper which will be extended</param>
        /// <param name="fileName">The filename which will be extended</param>
        /// <param name="partialUX">Defines whether the script is for a parial or not.</param>
        /// <returns>Returns an instance of MvcHtmlString containing the tag</returns>
        private static MvcHtmlString JavaScriptForUX(
            this HtmlHelper helper,
            string fileName,
            bool partialUX)
        {
            if (helper == null)
            {
                throw new ArgumentNullException("helper");
            }

            var controllerName = string.Empty;
            var controller = helper.ViewContext.Controller;
            if (controller != null)
            {
                var typeOfController = controller.GetType();
                controllerName = typeOfController.Name.Replace("Controller", string.Empty);
            }

            var areaName = GetAreaFromContext(helper.ViewContext);

            return JavaScript(
                helper,
                JavaScriptType.UX,
                areaName,
                controllerName,
                fileName,
                partialUX);
        }

        /// <summary>
        /// Renders an inclusion to a javascript file, casting it from the right
        /// javascripts repository.
        /// </summary>
        /// <param name="helper">The helper which will be extended</param>
        /// <param name="type">The type of javascript which will be loaded</param>
        /// <param name="areaName">The name of the area in which the controller sits</param>
        /// <param name="controllerName">The name of the controller for which the javascript exists. Should be used ONLY with type UX</param>
        /// <param name="fileName">The filename which will be extended</param>
        /// <param name="partialUX">The value indicating whether the js file is related to a partial or not.</param>
        /// <returns>Returns an instance of MvcHtmlString containing the tag</returns>
        private static MvcHtmlString JavaScript(
            this HtmlHelper helper,
            JavaScriptType type,
            string areaName,
            string controllerName,
            string fileName,
            bool partialUX)
        {
            if (helper == null)
            {
                throw new ArgumentNullException("helper");
            }
            
            var tag = new TagBuilder("script");

            // Here we check the consistency of type + controllerName
            // UX requires a controller name whereas other types can't accept a controllerName
            if (type == JavaScriptType.UX && string.IsNullOrEmpty(controllerName))
            {
                throw new JavaScriptTypeCannotAcceptControllerNameException(
                    type,
                    controllerName);
            }
            else if (type != JavaScriptType.UX && !string.IsNullOrWhiteSpace(controllerName))
            {
                throw new JavaScriptTypeCannotAcceptControllerNameException(
                    type,
                    controllerName);
            }

            // Checks and Treats the location
            const string VirtualPathIndicator = "~";
            const string FileExtension = ".js";

            if (fileName.EndsWith(FileExtension, StringComparison.OrdinalIgnoreCase))
            {
                fileName = fileName.Replace(
                    FileExtension,
                    string.Empty);
            }

            if (!fileName.Contains(VirtualPathIndicator))
            {
                if (type == JavaScriptType.Font)
                {
                    var themeName = helper.GetThemeFromActiveTenant().ToString();
                    
                    fileName = string.Concat(
                        "~/Content/Themes/",
                        themeName,
                        "/Fonts/",
                        fileName,
                        FileExtension);
                }
                else if (type == JavaScriptType.UX)
                {
                    fileName = string.Concat(
                        "~/Content/Scripts/",
                        type.ToString(),
                        "/",
                        areaName,
                        (!string.IsNullOrWhiteSpace(areaName) ? "/" : string.Empty),
                        controllerName,
                        (!string.IsNullOrWhiteSpace(controllerName) ? "/" : string.Empty),
                        (partialUX ? "Partials/" : string.Empty),
                        fileName,
                        FileExtension);
                }
                else if (type == JavaScriptType.Shared)
                {
                    fileName = string.Concat(
                        "~/Content/Scripts/",
                        type.ToString(),
                        "/",
                        areaName,
                        (!string.IsNullOrWhiteSpace(areaName) ? "/" : string.Empty),
                        fileName,
                        FileExtension);
                }
                else
                {
                    fileName = string.Concat(
                        "~/Content/Scripts/",
                        type.ToString(),
                        "/",
                        fileName,
                        FileExtension);
                }
            }

            fileName = VirtualPathUtility.ToAbsolute(fileName);
            
            // Add attributes
            tag.MergeAttribute("type", "text/javascript");
            tag.MergeAttribute("language", "javascript");
            tag.MergeAttribute("src", fileName);

            // Render tag
            var html = string.Concat(
                tag.ToString(TagRenderMode.StartTag),
                tag.ToString(TagRenderMode.EndTag));

            return MvcHtmlString.Create(html);
        }

        /// <summary>
        /// Retrieves the area from the context of the view.
        /// </summary>
        /// <param name="viewContext">The context of the view</param>
        /// <returns>Returns the name of the area from the context.</returns>
        private static string GetAreaFromContext(ViewContext viewContext)
        {
            const string AreaTokenKey = "area";
            var areaName = string.Empty;
            if (viewContext.RouteData.Values.ContainsKey(AreaTokenKey))
            {
                areaName = viewContext.RouteData.Values[AreaTokenKey] as string;
            }

            if (string.IsNullOrWhiteSpace(areaName) &&
                viewContext.RouteData.DataTokens.ContainsKey(AreaTokenKey))
            {
                areaName = viewContext.RouteData.DataTokens[AreaTokenKey] as string;
            }

            if (!string.IsNullOrWhiteSpace(areaName))
            {
                areaName = areaName.ToFirstUpper();
            }

            return areaName;
        }
    }
}


